/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.policy.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.notice.domain.dto.NoticeQueryCriteria;
import com.fzhucc.modules.pms.domain.dto.ProjectDesireQueryCriteria;
import com.fzhucc.modules.policy.domain.Policy;
import com.fzhucc.modules.policy.domain.PolicyMsgBox;
import com.fzhucc.modules.policy.domain.dto.PolicyQueryCriteria;
import com.fzhucc.modules.policy.domain.dto.PolicySeekDto;
import com.fzhucc.modules.policy.repository.PolicyRepository;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.thinktank.domain.Company;
import com.fzhucc.modules.thinktank.domain.CompanyMsgBox;
import com.fzhucc.modules.thinktank.domain.dto.CompanyBoxSeekDto;
import com.fzhucc.modules.thinktank.domain.dto.CompanyMsgBoxDto;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.policy.repository.PolicyMsgBoxRepository;
import com.fzhucc.modules.policy.domain.dto.PolicyMsgBoxDto;
import com.fzhucc.modules.policy.domain.dto.PolicyMsgBoxQueryCriteria;
import com.fzhucc.modules.policy.service.mapstruct.PolicyMsgBoxMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-03-13
 **/
@Service
@RequiredArgsConstructor
public class PolicyMsgBoxService {

    private final PolicyMsgBoxRepository policyMsgBoxRepository;

    private final UserRepository userRepository;

    private final PolicyRepository policyRepository;
    private final PolicyMsgBoxMapper policyMsgBoxMapper;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    public Map<String, Object> queryAll(PolicyMsgBoxQueryCriteria criteria, Pageable pageable) {
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        Page<PolicyMsgBox> page = policyMsgBoxRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<PolicyMsgBoxDto> map = page.map(policyMsgBoxMapper::toDto);
        List<PolicyMsgBoxDto> list = map.getContent();
        if (list != null) {
            for (PolicyMsgBoxDto policyMsgBoxDto : list) {
                Optional<Policy> res = policyRepository.findById(policyMsgBoxDto.getPolicyId());
                if (res.isPresent()) {
                    policyMsgBoxDto.setPolicy(res.get());
                }
            }
        }
        return PageUtil.toPage(map);
    }

    //根据不同设置不同的部门查看 处理  福建省;  或者  福建省;福州市;   或者 福建省;福州市;马尾区; 这种类型
    public String setCriteria(PolicyMsgBoxQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return orgArea;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//包含福建省 则查全部
                return null;
            } else {
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[2];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw new BadRequestException("用户ID未找到");
        }
    }


    public List<PolicyMsgBoxDto> queryAll(PolicyMsgBoxQueryCriteria criteria) {
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        return policyMsgBoxMapper.toDto(policyMsgBoxRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public PolicyMsgBoxDto findById(Integer id) {
        PolicyMsgBox policyMsgBox = policyMsgBoxRepository.findById(id).orElseGet(PolicyMsgBox::new);
        ValidationUtil.isNull(policyMsgBox.getId(), "PolicyMsgBox", "id", id);
        return policyMsgBoxMapper.toDto(policyMsgBox);
    }

    @Transactional(rollbackFor = Exception.class)
    public PolicyMsgBoxDto create(PolicyMsgBox resources) {
        return policyMsgBoxMapper.toDto(policyMsgBoxRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(PolicyMsgBox resources) {
        PolicyMsgBox policyMsgBox = policyMsgBoxRepository.findById(resources.getId()).orElseGet(PolicyMsgBox::new);
        ValidationUtil.isNull(policyMsgBox.getId(), "PolicyMsgBox", "id", resources.getId());
        policyMsgBox.copy(resources);
        policyMsgBoxRepository.save(policyMsgBox);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            policyMsgBoxRepository.deleteById(id);
        }
    }

    public void download(List<PolicyMsgBoxDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PolicyMsgBoxDto policyMsgBox : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("政策id", policyMsgBox.getPolicyId());
            map.put("咨询内容", policyMsgBox.getContent());
            map.put("联系方式", policyMsgBox.getPhone());
            map.put("咨询时间", policyMsgBox.getConsultationTime());
            map.put("咨询人姓名", policyMsgBox.getName());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public PolicyMsgBoxDto seek(PolicySeekDto resources) {
        PolicyMsgBox policyMsgBox = new PolicyMsgBox();
        Optional<Policy> res = policyRepository.findById(resources.getPolicyId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到该政策");
        }
        policyMsgBox.setPolicyId(resources.getPolicyId());
        policyMsgBox.setPhone(resources.getPhone());
        policyMsgBox.setConsultationTime(new Timestamp(new Date().getTime()));
        policyMsgBox.setContent(resources.getContent());
        policyMsgBox.setName(resources.getName());
        policyMsgBox.setOrgArea(res.get().orgArea);//政策的orgarea
        PolicyMsgBox policyMsgBox1 = policyMsgBoxRepository.save(policyMsgBox);
        return policyMsgBoxMapper.toDto(policyMsgBox1);
    }
}